<template>
  <div>
    <el-row class="config-margin">
      <el-col :span="7" class="line">
        <tree
          @addChild="addChild"
          @editChild="editChild"
          @deleteChild="deleteChild"
          @nodeClick="nodeClick"
          :open="true"
          :dealTree = "{add: true,delete:true,edit:true,move:false}"
          :treeData="treeData">
        </tree>
        <el-dialog :close-on-click-modal="false" :title="dialogObj.title" :visible.sync="dialogObj.isShow" width="30%" class="message-box">
          <el-form label-position="top" :rules="rules" ref="form" :model="dialogObj.form" class="">
            <el-form-item :label="$t('configLazyLoad.robotSeven.classification')">
              <el-input size="mini" v-model.trim="dialogObj.prentsName" :disabled="true"></el-input>
            </el-form-item>
            <el-form-item :label="$t('configLazyLoad.robotSeven.typeName')" prop="name">
              <el-input size="mini" v-model.trim="dialogObj.form.name"></el-input>
            </el-form-item>
            <el-form-item :label="$t('configLazyLoad.robotSeven.sortNum')" prop="order">
              <el-input size="mini" v-model.trim="dialogObj.form.order"></el-input>
              <span class="font12 help-tips">{{$t('configLazyLoad.robotSeven.sortText')}}</span>
            </el-form-item>
            <el-form-item :label="$t('configLazyLoad.robotSeven.remark')">
              <el-input size="mini" v-model.trim="dialogObj.form.note"></el-input>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="dialogObj.isShow = false" class="primary_btn">{{$t('configLazyLoad.robotSeven.cancel')}}</el-button>
            <el-button type="primary" @click="saveAddTree" class="primary_btn">{{$t('public.save')}}</el-button>
          </div>
        </el-dialog>
      </el-col>
      <el-col :span="17" class="line_right">
        <affix :label="$t('configLazyLoad.robotSeven.questionList')" class="margin-l">
          <div class="search clearbt">
            <div @keyup.enter="search" class="fl">
              <el-input
                size="mini"
                :placeholder="$t('configLazyLoad.robotSeven.pleaseInputSearchContent')"
                v-model="searchObj.name"
                style="width:300px"
              >
                <i
                  class="el-input__icon el-icon-search"
                  slot="suffix"
                  @click="search">
                </i>
              </el-input>
            </div>
            <div class="fr">
              <el-button class="primary_btn" type="primary" v-show="this.searchObj.type" @click="addQuestion">{{$t('configLazyLoad.robotSeven.addQuestion')}}</el-button>
              <el-button class="primary_btn" type="primary" @click="importExcel">{{$t('config.customer.importData')}}</el-button>
              <el-button class="primary_btn" type="primary" @click="exportExcel">{{$t('configLazyLoad.robotSeven.exportData')}}</el-button>
            </div>
          </div>
          <common-table :tableHead="tableHead" :data="tableData" :pagination="pagination" @operate="operate" @turnPage="search" type="selection" @selectionChange="selectionChange">
            <template slot="globalOperate">
              <el-button class="small_btn" type="text" @click.stop="globalOperate('delete')"><i class="iconfont icon-shanchu"></i><span class="font-color">&nbsp;{{$t('public.delete')}}</span></el-button>
              <el-button class="small_btn" type="text" @click.stop="globalOperate('stop')"><i class="iconfont icon-zuixiaohua circle transform"></i><span class="font-color">&nbsp;{{$t('config.channel.disabled')}}</span></el-button>
              <el-button class="small_btn" type="text" @click.stop="globalOperate('open')"><i class="iconfont icon-fasongchenggong circle"></i><span class="font-color">&nbsp;{{$t('config.channel.enabled')}}</span></el-button>
              <el-button class="small_btn" type="text" @click.stop="globalOperate('transfer')"><i class="iconfont icon-daochu1"></i><span class="font-color">&nbsp;{{$t('configLazyLoad.robotSeven.move')}}</span ></el-button>
            </template>
          </common-table>
        </affix>
      </el-col>
    </el-row>
    <el-dialog :close-on-click-modal="false" :title="commonDialog.title" :visible.sync="commonDialog.isShow" :class="[commonDialog.type === 'messageBox'? 'message-box':'']">
      <global-operate v-if="commonDialog.type === 'messageBox'" :message="messageBox" @confirm="confirm" @close="close"></global-operate>
      <import-question v-else-if="commonDialog.type ==='import'" @close="close" :isShow="commonDialog.isShow"></import-question>
      <add-question v-if="commonDialog.type === 'add'||commonDialog.type === 'update'" @dialogaddquestion="dialogaddquestion" @formData="formData" :oldData="oldData"></add-question>
    </el-dialog>
  </div>
</template>
<script>
  import tree from '../agentConfig/tree/Base/Tree.vue'
  import {deepClone} from '@/utils/m7Utils'
  import {checkform} from '@/utils/validate'
  import * as uuid from 'uuid'
  import affix from '../../../ui-modules/affix/Affix.vue'
  import commonTable from './base/CommonTable'
  import AddQuestion from './AddQuestion'
  import globalOperate from './base/globalOperate.vue'
  import importQuestion from './base/ImportQuestionTemplate.vue'
  export default {
    name: 'questionManage',
    data () {
      let validate1 = (rule, value, callback) => {
        if (value === '') {
          callback(new Error(this.$t('validate.required')))
        } else if (checkform(value, 'Number')) {
          callback(new Error(this.$t('customer.shouldBeNumber')))
        } else {
          callback()
        }
      }
      return {
        depts: [],
        pagination: {
          currentPage: 0,
          count: 0
        },
        searchObj: {
          name: '',
          type: '',
          page: 1,
          limit: 10
        },
        ids: '',
        messageBox: {
          type: '',
          content: '',
          size: ''
        },
        treeData: {},
        tableData: [],
        tableHead: [
          {prop: 'name', label: this.$t('configLazyLoad.robotSeven.question1'), special: 'click', sort: false},
          {prop: 'typeName', label: this.$t('report.sort'), sort: true},
          {prop: 'lastTime', label: this.$t('customer.updateTime'), sort: true},
          {prop: 'status', label: this.$t('monitor.state'), special: 'color', sort: true},
          {prop: 'likenessNum', label: this.$t('configLazyLoad.robotSeven.similarQues'), sort: true},
          {prop: 'hits', label: this.$t('report.hitsNumber'), sort: true},
          {prop: 'isPush', label: this.$t('configLazyLoad.robotSeven.isPushques'), sort: true},
          {prop: 'useful', label: this.$t('configLazyLoad.robotSeven.helpfulNumber'), sort: true},
          {prop: 'useless', label: this.$t('configLazyLoad.robotSeven.noHelpfulNumber'), sort: true}
        ],
        dialogObj: {
          isShow: false,
          title: '',
          form: {
            _id: '',
            pId: '',
            name: '',
            order: 0,
            treePath: '',
            note: ''
          },
          type: 'add',
          prentsName: ''
        },
        commonDialog: {
          isShow: false,
          title: '',
          type: '',
          size: ''
        },
        rules: {
          name: [
            {required: true, message: this.$t('validate.required'), trigger: 'blur'}
          ],
          order: [
            {validator: validate1, trigger: 'blur'}
          ]
        },
        addQuestionShow: {
          ifShow: false
        },
        oldData: {}
      }
    },
    components: {
      tree,
      commonTable,
      affix,
      globalOperate,
      importQuestion,
      AddQuestion
    },
    methods: {
      nodeClick (val) {
        if (val.pId) {
          this.searchObj.type = val._id
          this.oldData.type = val._id
        } else {
          this.searchObj.type = ''
        }
        this.searchObj.name = ''
        this.search()
      },
      globalOperate (type) {
        if (!this.ids) {
          this.$message.error(this.$t('configLazyLoad.robotSeven.tickQues'))
          return
        }
        this.messageBox.type = type
        this.commonDialog.type = 'messageBox'
        this.commonDialog.size = 'tiny'
        this.commonDialog.isShow = true
        if (type === 'delete') {
          this.messageBox.content = this.$t('configLazyLoad.robotSeven.deleteQues1')
          this.commonDialog.title = this.$t('public.delete')
        } else if (type === 'stop') {
          this.commonDialog.title = this.$t('sms.stop')
          this.messageBox.content = this.$t('configLazyLoad.robotSeven.isStopQues')
        } else if (type === 'open') {
          this.commonDialog.title = this.$t('sms.reuse')
          this.messageBox.content = this.$t('configLazyLoad.robotSeven.isEnbleQues')
        } else if (type === 'transfer') {
          this.commonDialog.title = this.$t('configLazyLoad.robotSeven.transferQues')
          this.messageBox.content = this.depts
        }
      },
      confirm (val) {
        let action = ''
        let data = {ids: this.ids}
        if (this.messageBox.type === 'delete') {
          action = 'deleteQuestion'
        } else if (this.messageBox.type === 'stop') {
          action = 'disabledQuestion'
        } else if (this.messageBox.type === 'open') {
          action = 'activeQuestion'
        } else if (this.messageBox.type === 'transfer') {
          action = 'moveQuestion'
          data.type = val
        }
        this.$store.dispatch(action, data).then(() => {
          this.commonDialog.isShow = false
          this.search()
        })
      },
      close () {
        this.commonDialog.isShow = false
        this.commonDialog.size = ''
      },
      operate (event) {
        let type = event.type
        if (type === 'name') {
          this.$store.dispatch('getQuestionById', event.val._id).then((res) => {
            if (res.success) {
              let question = res.question
              this.oldData = question
              this.oldData.isAdd = true
              this.commonDialog = {
                isShow: true,
                type: 'update',
                title: this.$t('configLazyLoad.robotSeven.quesConfigEdit')
              }
            } else {
              this.$message({
                type: 'error',
                message: res.message
              })
            }
          })
        }
      },
      selectionChange (val) {
        let arr = []
        val.forEach((item) => {
          arr.push(item._id)
        })
        this.ids = arr.join(',')
      },
      search (page) {
        this.searchObj.page = typeof page === 'number' ? page : 1
        this.$store.dispatch('queryQuestions', this.searchObj).then((res) => {
          if (res.success) {
            this.pagination.count = res.count
            this.pagination.currentPage = this.searchObj.page
            this.ids = ''
            let list = res.list
            let arr = []
            for (let i = 0; i < list.length; i++) {
              let question = list[i]
              // 推送问题
              if (question.isPush === '1') {
                question.isPush = this.$t('public.yes')
              } else {
                question.isPush = this.$t('public.no')
              }
              if (!question.hits) {
                question.hits = 0
              }
              if (question.status === '1') {
                question.status = {color: '#459ae9', name: this.$t('sms.reuse')}
              } else {
                question.status = {color: '#ff6b69', name: this.$t('qualityCheck.stoped')}
              }
              question.likenessNum = question.likeness.length
              question.typeName = this.getDeptName(question.type)
              if (!question.useful) {
                question.useful = 0
              }
              if (!question.useless) {
                question.useless = 0
              }
              arr.push({ _id: question._id, likenessNum: question.likenessNum, isPush: question.isPush, hits: question.hits, name: question.name, status: question.status, typeName: question.typeName, lastTime: question.lastTime, useful: question.useful, useless: question.useless })
            }
            this.tableData = arr
          }
        })
      },
      addQuestion () {
        this.oldData = {
          isAdd: true,
          n: Math.random(),
          type: this.searchObj.type
        }
        this.commonDialog = {
          isShow: true,
          title: this.$t('configLazyLoad.robotSeven.addQues1'),
          type: 'add'
        }
      },
      exportExcel () {
        this.$store.dispatch('exportQuestion', {name: this.searchObj.name, type: this.searchObj.type, page: 1, limit: 10, account: this.$store.state.session.account.account}).then(() => {
        })
      },
      importExcel () {
        this.commonDialog.type = 'import'
        this.commonDialog.title = this.$t('configLazyLoad.robotSeven.importQues1')
        this.commonDialog.size = ''
        this.commonDialog.isShow = true
      },
      saveAddTree () {
        this.$refs.form.validate((valid) => {
          if (valid) {
            let dispatchName = ''
            if (this.dialogObj.type === 'add') {
              dispatchName = 'addQuesType'
            } else {
              dispatchName = 'updateQuesType'
            }
            this.$store.dispatch(dispatchName, this.dialogObj.form)
              .then(resp => {
                this.restDeptTree().then(() => {
                  this.search()
                })
                if (resp.success) {
                  this.$message({
                    type: 'success',
                    message: this.$t('channel.saveSuccess')
                  })
                }
              })
            this.dialogObj.isShow = false
          }
        })
      },
      addChild (val) {
        this.dialogObj.isShow = true
        this.dialogObj.title = this.$t('config.channel.addCategory')
        this.dialogObj.type = 'add'
        this.$nextTick(() => {
          this.dialogObj.form.order = 0
        })
        let temp = val
        this.dialogObj.form.pId = temp._id
        this.dialogObj.form._id = uuid.v1()
        this.dialogObj.prentsName = temp.name
        this.dialogObj.form.treePath = `${temp.treePath}${this.dialogObj.form._id}/`
        this.dialogObj.form.name = ''
        this.dialogObj.form.note = ''
        if (this.$refs.form) {
          this.$refs.form.resetFields()
        }
      },
      editChild (val) {
        this.dialogObj.isShow = true
        this.dialogObj.title = this.$t('webchat.editQuickRelySort')
        this.dialogObj.type = 'update'
        let temp = deepClone(val)
        delete temp.children
        this.dialogObj.form.pId = temp.pId
        this.dialogObj.form._id = temp._id
        this.dialogObj.form.treePath = temp.treePath
        this.dialogObj.prentsName = this.getDeptName(temp.pId)
        this.dialogObj.form.name = temp.name
        this.dialogObj.form.note = temp.note
        this.dialogObj.form.order = temp.order
        if (this.$refs.form) {
          this.$refs.form.validate(() => {})
        }
      },
      deleteChild (val) {
        if (val.children && val.children.length > 0) {
          this.$message({
            type: 'warning',
            message: this.$t('configLazyLoad.robotSeven.deleErrorAfter')
          })
          return
        }
        this.$confirm(this.$t('config.agent.confirmDel', {name: val.name}), this.$t('public.tip'), {
          confirmButtonText: this.$t('public.confirm'),
          cancelButtonText: this.$t('public.cancel'),
          cancelButtonClass: 'primary_btn',
          confirmButtonClass: 'primary_btn',
          type: 'warning'
        })
          .then(() => {
            this.$store.dispatch('delQuesType', {typeId: val._id})
              .then(resp => {
                this.restDeptTree().then(() => {
                  this.search()
                })
                if (resp.success) {
                  this.$message({
                    type: 'success',
                    message: this.$t('config.agent.successDel')
                  })
                }
              })
          })
          .catch(() => {
          })
      },

      getDeptName (id) {
        if (!id) {
          return this.$t('public.all')
        }
        let depsObj = this.depts.filter(item => item._id === id)[0]
        return depsObj ? depsObj.name ? depsObj.name : '' : ''
      },
      restDeptTree () {
        return this.$store.dispatch('getCache', {type: 'quesTypes', loadFromServer: true})
          .then((depts) => {
            let arr = []
            this.depts = depts || []
            dealDept(this.depts, arr, '')
            this.treeData = arr[0] || {}
            this.$store.commit('config/robotConfig/REFRESH_TREE')
          })
      },
      dialogaddquestion (showAdd) {
        this.commonDialog.isShow = showAdd
      },
      formData (form) {
        if (this.commonDialog.type === 'add') {
          form._id = uuid.v1()
          this.$store.dispatch('addquestion', form).then((rep) => {
            if (rep.success) {
              this.dialogaddquestion(false)
              this.search()
              this.$message(this.$t('configLazyLoad.robotSeven.addQuesSuccess'))
            } else {
              this.$message({
                message: rep.message,
                type: 'error'
              })
            }
          })
        }
        if (this.commonDialog.type === 'update') {
          this.$store.dispatch('updateQuestion', form).then((rep) => {
            if (rep.success) {
              this.dialogaddquestion(false)
              this.search()
              this.$message(this.$t('configLazyLoad.robotSeven.editQuesEerror'))
            } else {
              this.$message({
                message: rep.message || this.$t('message.randomKey_not_find'),
                type: 'error'
              })
            }
          })
        }
      }
    },
    deactivated () {
      this.commonDialog.isShow = false
      this.dialogObj.isShow = false
    },
    beforeMount () {
      this.restDeptTree().then(() => {
        this.search()
      })
    }
  }
  function dealDept (depts, arr, key) {
    for (let i in depts) {
      let dept = depts[i]
      if (dept.pId === key) {
        let obj = {
          _id: dept._id,
          type: 'robot',
          treePath: dept.treePath,
          note: dept.note,
          pId: dept.pId,
          name: dept.name,
          order: dept.order || 0,
          children: []
        }
        arr.push(obj)
        dealDept(depts, obj.children, dept._id)
      }
    }
  }
</script>
<style lang="stylus" scoped>
  @import '../../../../assets/common.styl'
  .config-margin
    margin-top 20px
  .search
    height 30px
    padding-bottom 10px
  .font-color
    color $cf-gray1
  .line
    overflow-x auto
  .margin-l
    margin-left 15px
  .circle
    border 1px solid $c-main
    border-radius 50%
    font-size 14px
    display inline-block
    width 15px
    height 15px
    line-height 15px
  .transform
    transform rotate(-35deg)
  .help-tip
    color $cf-gray5
  .line_right
    border-left 1px solid #ccc
</style>
